#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangbetlmgzzqPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_betlmgzzq_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "博尔塔拉蒙古自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }

    def start_requests(self):
        for source, county, url in [
            ['博尔塔拉蒙古自治州人民政府', "", "http://www.xjboz.gov.cn/zwgk/zfxxgk/zc/zzzwj/gfxwj.htm"],
            ['博尔塔拉蒙古自治州人民政府', "", "http://www.xjboz.gov.cn/zwgk/zfxxgk/zc/zzzwj/zfwj/bzzf.htm"],
            ['博尔塔拉蒙古自治州人民政府', "", "http://www.xjboz.gov.cn/zwgk/zfxxgk/zc/zzzwj/zfwj/bzzbf.htm"],
            ['博尔塔拉蒙古自治州发展和改革委员会', "", "http://www.xjboz.gov.cn/zwgk/gkpt/fgw/gksx/bmwj.htm"],
            ['博尔塔拉蒙古自治州科技局', "", "http://www.xjboz.gov.cn/zwgk/gkpt/kjj/gksx/bmwj.htm"],
            ['博尔塔拉蒙古自治州工业和信息化局', "", "http://www.xjboz.gov.cn/zwgk/gkpt/gyhxxhj/gksx/bmwj.htm"],
            ['博尔塔拉蒙古自治州财政局', "", "http://www.xjboz.gov.cn/zwgk/gkpt/czj/gksx/bmwj.htm"],
            ['博尔塔拉蒙古自治州人力资源和社会保障局', "", "http://www.xjboz.gov.cn/zwgk/gkpt/rsj/gksx/bmwj.htm"],
            ['博尔塔拉蒙古自治州商务局', "", "http://www.xjboz.gov.cn/zwgk/gkpt/swj/gksx/bmwj.htm"],
            ['博乐市人民政府', "博乐市", "http://www.xjbl.gov.cn/zwgk/zfxxgk/zc/blswj/zfwj/bszf.htm"],
            ['博乐市人民政府', "博乐市", "http://www.xjbl.gov.cn/zwgk/zfxxgk/zc/blswj/zfwj/bszbf.htm"],
            ['博乐市人民政府', "博乐市", "http://www.xjbl.gov.cn/zwgk/zfxxgk/zc/blswj/gfxwj.htm"],
            ['阿拉山口市人民政府', "阿拉山口市", "http://www.alsk.gov.cn/zwgk/fdzdgknr/jcxxgk/zfwj.htm"],
            ['阿拉山口市人民政府', "阿拉山口市", "http://www.alsk.gov.cn/zwgk/fdzdgknr/jcxxgk/gfxwj.htm"],
            ['精河县人民政府', "精河县", "http://www.xjjh.gov.cn/zwgk/zfxxgk/zc/jhxwj/zfwj/jzf.htm"],
            ['精河县人民政府', "精河县", "http://www.xjjh.gov.cn/zwgk/zfxxgk/zc/jhxwj/zfwj/jzbf.htm"],
            ['精河县人民政府', "精河县", "http://www.xjjh.gov.cn/zwgk/zfxxgk/zc/jhxwj/gfxwj.htm"],
            ['精河县科技局', "精河县", "http://www.xjjh.gov.cn/zwgk/bmxxgk/zfgzbm/xkxjsj/kjxx/kjzc.htm"],
            ['温泉县人民政府', "温泉县", "http://www.xjwq.gov.cn/zwgk/zfxxgk/zc/wqxwj/zfwj/wzf.htm"],
            ['温泉县人民政府', "温泉县", "http://www.xjwq.gov.cn/zwgk/zfxxgk/zc/wqxwj/zfwj/wzbf.htm"],
            ['温泉县人民政府', "温泉县", "http://www.xjwq.gov.cn/zwgk/zfxxgk/zc/wqxwj/gfxwj.htm"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//table//tr/td/a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::td[string-length(string(.))>=5] | "
                "//ul[contains(@class, 'list')]/li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text and response.xpath('//a[text()="下页"]'):
                total_page = response.xpath(""".""").re_first(r"""/(\d+)页""")
                if total_page is None:
                    total_page = response.xpath('//a[text()="下页"]/@href').re_first(r"/(\d+)\.htm")
                print(response.url, "page:", total_page)
                for page_num in range(1, int(int(total_page) / 1 + 1)):
                    url = response.url.replace('.htm', f'/{page_num}.htm')
                    yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_betlmgzzq_policy".split())
